//
//  YHBackgroundTask.swift
//  Adorbee
//
//  Created by amovision on 2025/3/24.
//

import UIKit

public class YHBackgroundTask {
  private var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = .invalid
  private let application: UIApplication
  private let expirationHandler: (() -> Void)?

  public init(application: UIApplication = .shared, expirationHandler: (() -> Void)? = nil) {
    self.application = application
    self.expirationHandler = expirationHandler
  }

  public func beginBackgroundTask() {
    backgroundTaskIdentifier = application.beginBackgroundTask { [weak self] in
      self?.endBackgroundTask()
      self?.expirationHandler?()
    }
    if backgroundTaskIdentifier == .invalid {
      print("Failed to begin background task.")
    }
  }

  public func endBackgroundTask() {
    if backgroundTaskIdentifier != .invalid {
      application.endBackgroundTask(backgroundTaskIdentifier)
      backgroundTaskIdentifier = .invalid
    }
  }
}
